﻿using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using CloudShot.Editor.CanvasFigures;
using CloudShot.Interfaces;
using CloudShot.Properties;
using Color = System.Drawing.Color;

namespace CloudShot.Editor.Tools
{
  internal class TextTool : RectangleTool
  {
    private readonly IEnumerable<FigureColorScheme> _figureColorSchemes;
    private CanvasText _canvasText = null;


    public TextTool(IDrawingCanvas drawingCanvas, FigureSettings figureSettings, IEnumerable<FigureColorScheme> figureColorSchemes, Section changeToolsSection, Section resetToolSection, Cursor cursor)
      : base(drawingCanvas, figureSettings, changeToolsSection, resetToolSection, cursor)
    {
      _figureColorSchemes = figureColorSchemes;
    }

    public override void OnMouseDown(MouseEventArgs e)
    {
      _canvasText = new CanvasText(Resources.TextTool_DefaultText, e.X, e.Y, 1, 1)
      {
        BorderColor = FigureSettings.BorderColor,
        BackColor = FigureSettings.BackColor,
        BorderWidth = FigureSettings.BorderWidth,
        BackgroundOpacity = FigureSettings.BackgroundOpacity,
        TextColor = FigureSettings.TextColor,
        FontSize = FigureSettings.FontSize,
        LineType = FigureSettings.LineType
      };

      AddNewObject(Canvas, _canvasText);
    }

    public override void OnMouseUp(MouseEventArgs e)
    {
      base.OnMouseUp(e);

      if (_canvasText != null)
      {
        Canvas.BeginTextEdit(_canvasText);
        _canvasText = null;
      }
    }

    public void AddTextToGraphicList(CanvasRectangleBase rectangle)
    {
      Color textColor = FindBestTextColor(rectangle);

      var text = new CanvasText(Resources.TextTool_DefaultTextFromRect, rectangle.Rectangle.X, rectangle.Rectangle.Y, rectangle.Rectangle.Width, rectangle.Rectangle.Height)
      {
        BackColor = rectangle.BackColor,
        BorderColor = rectangle.BorderColor,
        BorderWidth = rectangle.BorderWidth,
        LineType = rectangle.LineType,
        BackgroundOpacity = rectangle.BackgroundOpacity,
        FontSize = FigureSettings.FontSize,
        IsSelected = true,
        TextColor = textColor
      };

      Canvas.GraphicsList.Add(text);
      Canvas.RefreshCanvas(text.GetBoundingBox());
      Canvas.BeginTextEdit(text);
    }

    private Color FindBestTextColor(CanvasRectangleBase rectangle)
    {
      Color textColor = rectangle.BorderColor;

      if (rectangle.BackgroundOpacity > 0)
      {
        //find the best text color for current figure
        FigureColorScheme colorScheme = _figureColorSchemes.FirstOrDefault(f => f.BackColor == rectangle.BackColor);

        if (colorScheme != null)
          textColor = colorScheme.TextColor;
      }
      return textColor;
    }

    protected override string GetHintEnterText()
    {
      return HintResources.TextTool_Enter;
    }
  }
}